// pages/login1/login.js
const mybehavior = require("../../behaviors/requests")

Page({

  /**
   * 页面的初始数据
   */
  behaviors: [mybehavior],
  data: {
    base_urlstr: "https://logisticsengineering.gree.com",
    login_style_yzm: "position: absolute;width: 160rpx;height: 32rpx;left: 48rpx;top: 76rpx;color: #1A1A1A;line-height: 32rpx;font-size: 32rpx;font-weight: 600;",
    login_style_user: "position: absolute;width: 160rpx;height: 32rpx;left: 282rpx;top: 76rpx;color: #1A1A1A;line-height: 32rpx;font-size: 32rpx;font-weight: 250;",
    login_style_flag: "position: absolute;width: 94rpx;height: 12rpx;left: 64rpx;top: 104rpx;background-color: #5555FF;border-radius: 6rpx 6rpx 6rpx 6rpx;",
    login_style_show: true,
    yam_word: "发送验证码",
    employee_num: "",
    email: "",
    password: "",
    phone_num: "",
    verification_code: "",
    count: 0,
    id_number: "",
    yzm_show: false,
    yam_btn_disabled: false,
    yam_btn: "primary",
    login_btn1: true,
    login_btn2: true,
    eye_show: "closed-eye",
    password_show: true,
    yzm_btn_style: "color: #aeaeff;",
    checked: false,
    email_or_employee_num: "",
    checked: false,
    show_privacy: false,
    privacy_name: "《格力智慧GMS小程序隐私协议》",
    name: "",
    yzm_show: false,
    captcha: "",
    imageSrc: ""


  },
  handleOpenPrivacyContract() {
    // 打开隐私协议页面
    wx.openPrivacyContract({
      success: () => { }, // 打开成功
      fail: () => { }, // 打开失败
      complete: () => { }
    })
  },

  onChange(event) {
    this.setData({
      checked: event.detail,
    });
    // if (event.detail == true) {
    //     this.showPrivacy()
    // }
  },
  onCorifm1() {
    this.setData({
      show_privacy: false
    })
  },
  onClose1() {
    this.setData({
      show_privacy: false
    })
  },
  backLogin() {
    wx.reLaunch({
      url: '/pages/login1/login',
    })
  },

  onClose() {
    this.setData({
      yzm_show: false,
    })
  },
  showPassword() {
    if (this.data.eye_show == "eye-o") {
      this.setData({
        eye_show: "closed-eye",
        password_show: true

      })
    } else {
      this.setData({
        eye_show: "eye-o",
        password_show: false

      })
    }
  },
  checkLoginBtn(e) {
    console.log(e.currentTarget.dataset.data);
    let key = e.currentTarget.dataset.data
    if (this.data.phone_num != "") {
      this.setData({
        yzm_btn_style: "color: #5555FF;"

      })
    } else {
      this.setData({
        yzm_btn_style: "color: #aeaeff;"

      })
    }
    if (key == "login_btn1") {
      if (this.data.phone_num != "" && this.data.email_or_employee_num && this.data.name) {
        this.setData({
          login_btn1: false,
          login_btn2: false,

        })
      } else {
        this.setData({
          login_btn1: true,
          login_btn2: true,

        })
      }
    } else {
      if (this.data.name != "" && this.data.phone_num != "") {
        this.setData({
          login_btn2: false,

        })
      } else {
        this.setData({
          login_btn2: true,

        })
      }
    }
  },
  // 验证码登录
  yzmLogin() {
    let style1 = "position: absolute;width: 160rpx;height: 32rpx;left: 48rpx;top: 76rpx;color: #1A1A1A;line-height: 32rpx;font-size: 32rpx;font-weight: 600;"
    let style2 = "position: absolute;width: 160rpx;height: 32rpx;left: 282rpx;top: 76rpx;color: #1A1A1A;line-height: 32rpx;font-size: 32rpx;font-weight: 250;"
    let style3 = "position: absolute;width: 94rpx;height: 12rpx;left: 64rpx;top: 104rpx;background-color: #5555FF;border-radius: 6rpx 6rpx 6rpx 6rpx;"
    this.setData({
      login_style_show: true,
      login_style_yzm: style1,
      login_style_user: style2,
      login_style_flag: style3,
    })
  },

  // 账号登录
  userLogin() {
    let style1 = "position: absolute;width: 160rpx;height: 32rpx;left: 48rpx;top: 76rpx;color: #1A1A1A;line-height: 32rpx;font-size: 32rpx;font-weight: 250;"
    let style2 = "position: absolute;width: 160rpx;height: 32rpx;left: 282rpx;top: 76rpx;color: #1A1A1A;line-height: 32rpx;font-size: 32rpx;font-weight: 600;"
    let style3 = "position: absolute;width: 94rpx;height: 12rpx;left: 298rpx;top: 104rpx;background-color: #5555FF;border-radius: 6rpx 6rpx 6rpx 6rpx;"
    this.setData({
      login_style_show: false,
      login_style_yzm: style1,
      login_style_user: style2,
      login_style_flag: style3,
    })
  },

  // 发送按钮倒计时
  sentBtn() {
    var a = this.data.count
    var t = this.data.yam_word
    if (a < 60) {
      this.setData({
        yam_word: t - 1,
        count: a + 1,
      })
      setTimeout(() => {
        this.sentBtn()
      }, 1000)
    } else {
      this.setData({
        yam_word: "发送验证码"
      })

    }

  },
  // 发送验证码
  sentCode() {



    var url = "https://logisticsengineering.gree.com/gm_user/gm_get_verification_code2";
    var data = {
      captcha: this.data.captcha,
      phone_num: this.data.phone_num,
    }
    console.log("发送验证码", data)
    this.post(url, data).then(res => {
      console.log("发送验证码返回信息", res)
      if (res.code == 20000) {
        this.setData({
          yzm_show: false,
          captcha: "",
          yam_btn_disabled: true,
          yam_word: 60,
          count: 0,
        })
        this.sentBtn()

        wx.showToast({
          title: res.msg,
          icon: "success"
        });
      } else {

        wx.showToast({
          title: res.msg,
          icon: "error"
        })
      }
    }).catch(err => {

      wx.showToast({
        title: err.msg,
        icon: 'error'
      })
    })



  },


  // 获取图形验证码
  BerforeSentCode() {
    if (this.data.checked == false) {
      wx.showToast({
        title: '请阅读并勾选同意《隐私协议》',
        icon: 'none'
      })

    } else {

      wx.showLoading({
        title: '加载中....',
      })
      var url = "https://logisticsengineering.gree.com/gm_user/gm_get_captcha";
      var data = {
        phone_num: this.data.phone_num,
      }
      let self = this

      wx.request({
        url: url,
        data: data,
        responseType: 'arraybuffer',
        success(res) {
          if (res.statusCode == 200) {
            const arrayBuffer = res.data;
            // 将 ArrayBuffer 转为 Base64
            const base64 = wx.arrayBufferToBase64(arrayBuffer);
            // 直接用作图片源（需后台返回完整Base64带前缀）
            self.setData({
              imageSrc: 'data:image/png;base64,' + base64,
              yzm_show: true,
            });

          } else {
            wx.showToast({
              title: '手机号有误，请重新确认！',
              icon: 'none'
            })
          }

          wx.hideLoading()

        }
      });

    }

  },

  onCloseLogin() {
    this.setData({
      yzm_show: false,
      captcha: ""
    })
  },
  onConfirmLogin() {
    if (this.data.captcha == "") {
      wx.showToast({
        title: '请输入图形验证码！',
        icon: 'none'
      })
    } else {

      this.sentCode()
    }
  },




  // 内部人员
  innerLogin() {
    if (this.data.checked == false) {
      wx.showToast({
        title: '请阅读并勾选同意《隐私协议》',
        icon: 'none'
      })

    } else {
      wx.showLoading({
        title: '注册中'
      })
      var url = this.data.base_urlstr + "/gm_user/wx_register_inner_user";
      var data = {
        phone_num: this.data.phone_num,
        verification_code: this.data.verification_code,
        email_or_employee_num: this.data.email_or_employee_num,
        name: this.data.name,
      }
      console.log("内部人员", data)
      this.post(url, data).then(res => {
        setTimeout(function () {
          wx.hideLoading()
        }, 2000)
        console.log("手机验证码登录返回信息", res)

        if (res.code == 20000) {
          this.setData({
            yzm_show: false
          })
          wx.setStorageSync('email', res.data.email_or_employee_num)
          wx.setStorageSync('name', res.data.name)
          wx.setStorageSync('phone_num', res.data.phone_num)
          wx.setStorageSync('_id', res.data._id)
          wx.setStorageSync('token', res.data.token)
          wx.setStorageSync('ID_number', res.data.ID_number)
          wx.redirectTo({
            url: '/pages/home1/home1',
          })
          wx.showToast({
            title: res.msg,
            icon: "success"
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: "error"
          })
        }
      }).catch(err => {
        wx.showToast({
          title: err.msg,
          icon: 'error'
        })
      })
    }

  },
  // 外部
  outerLogin() {
    if (this.data.checked == false) {
      wx.showToast({
        title: '请阅读并勾选同意《隐私协议》',
        icon: 'none'
      })
    } else {
      wx.showLoading({
        title: '注册中'
      })
      var url = this.data.base_urlstr + "/gm_user/wx_register_outer_user";
      var data = {
        name: this.data.name,
        phone_num: this.data.phone_num,
        ID_number: this.data.id_number,
        verification_code: this.data.verification_code
      }
      this.post(url, data).then(res => {
        setTimeout(function () {
          wx.hideLoading()
        }, 2000)
        console.log("外部", res)
        if (res.code == 20000) {
          wx.setStorageSync('email', res.data.email_or_employee_num)
          wx.setStorageSync('name', res.data.name)
          wx.setStorageSync('phone_num', res.data.phone_num)
          wx.setStorageSync('_id', res.data._id)
          wx.setStorageSync('token', res.data.token)
          wx.setStorageSync('ID_number', res.data.ID_number)
          wx.showToast({
            title: res.msg,
            icon: "success"
          });
          wx.redirectTo({
            url: '/pages/home1/home1',
          })
        } else {
          wx.showToast({
            title: res.msg,
            icon: "error"
          })
        }
      }).catch(err => {
        wx.showToast({
          title: err.msg,
          icon: 'error'
        })
      })
    }

  },
  getYzm(e) {
    console.log("验证码", e.detail.value);
    this.phoneLogin(e.detail.value)
  },
  // 手机验证码登录
  phoneLogin(e) {
    if (this.data.phone_num == "" || e == "") {
      wx.showToast({
        title: '不能为空',
        icon: 'error'
      })

    } else {
      wx.showLoading({
        title: '登录中'
      })
      var url = this.data.base_urlstr + "/wx_login_in_by_verification_code";
      var data = {
        phone_num: this.data.phone_num,
        verification_code: e,
      }
      console.log("手机验证码登录", data)
      this.post(url, data).then(res => {
        setTimeout(function () {
          wx.hideLoading()
        }, 2000)
        console.log("手机验证码登录返回信息", res)

        if (res.code == 20000) {
          this.setData({
            yzm_show: false
          })
          wx.setStorageSync('token', res.data.token)
          wx.setStorageSync('name', res.data.name)
          wx.setStorageSync('phone_num', this.data.phone_num)

          const pages = getCurrentPages();
          const length = pages.length;
          if (length > 1) {
            let i = 1;
            while (length - i >= 0) {
              const page = pages[length - i];
              if (page.route != "pages/login/login") {
                wx.navigateTo({
                  url: "/" + page.route,
                })
                return;
              }
              i += 1;
            }
            wx.redirectTo({
              url: '/pages/home1/home1',
            })

          } else {
            wx.redirectTo({
              url: '/pages/home1/home1',
            })
          }
          this.setData({
            email: "",
            password: "",
          })
          wx.showToast({
            title: res.msg,
            icon: "success"
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: "error"
          })
        }
      }).catch(err => {
        wx.showToast({
          title: err.msg,
          icon: 'error'
        })
      })
    }

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})